import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, Resolve, RouterStateSnapshot} from '@angular/router';
import {HomeService} from '../../services/home.service';
import {first} from 'rxjs/operators';
import {forkJoin, Observable} from 'rxjs';

/**
 * Resolve 守卫，预先获取组件数据
 * 使用真实 api，很有可能数据返回有延迟，导致无法即时显示。 在这种情况下，直到数据到达前，显示一个空的组件不是最好的用户体验。
 * https://angular.cn/guide/router#resolve-pre-fetching-component-data
 */
@Injectable()
export class HomeResolverService implements Resolve<any> {

  constructor(private homeService: HomeService) {
  }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | Promise<any> | any {
    return forkJoin([
      this.homeService.userInfo(),
      this.homeService.listMenu()
    ]).pipe(first());
  }
}
